/* Copyright (C) 1999-2005 by Peter Eastman

   This program is free software; you can redistribute it and/or modify it under the
   terms of the GNU General Public License as published by the Free Software
   Foundation; either version 2 of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but WITHOUT ANY 
   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */

package artofillusion;

import artofillusion.math.*;
import artofillusion.object.*;
import artofillusion.ui.*;
import buoy.event.*;
import java.awt.*;

/** RotateMeshTool is an EditingTool used for rotating the vertices of TriangleMesh objects. */

public class RotateMeshTool extends EditingTool
{
  private boolean noSelection, notOnHandle, only2D;
  private Point clickPoint, centerPoint;
  private Vec3 rotCenter, baseVertPos[];
  private int hdirection, vdirection, whichAxis;
  private UndoRecord undo;
  private MeshEditController controller;
  
  public static final int HANDLE_SIZE = 5;
  private static Image icon, selectedIcon;
  private static final double DRAG_SCALE = Math.PI/360.0;
  private static final int XAXIS = 0;
  private static final int YAXIS = 1;
  private static final int ZAXIS = 2;

  public RotateMeshTool(EditingWindow fr, MeshEditController controller, boolean only2D)
  {
    super(fr);
    this.controller = controller;
    this.only2D = only2D;
    icon = loadImage("rotatePoints.gif");
    selectedIcon = loadImage("selected/rotatePoints.gif");
  }

  public void activate()
  {
    super.activate();
    
    MeshViewer view = (MeshViewer) theWindow.getView();
    Mesh mesh = (Mesh) controller.getObject().object;
    MeshVertex v[] = mesh.getVertices();
    Camera cam = view.getCamera();
    int selected[] = controller.getSelectionDistance();
    noSelection = false;
    for (int i = 0; i < selected.length; i++)
      if (selected[i] == 0)
         {
           theWindow.setHelpText(Translate.text("rotateMeshTool.helpText"));
           BoundingBox bounds = findSelectionBounds(v, cam);
           rotCenter = new Vec3((bounds.minx+bounds.maxx)/2.0, (bounds.miny+bounds.maxy)/2.0, (bounds.minz+bounds.maxz)/2.0);
           rotCenter = cam.getViewToWorld().times(rotCenter);
           return;
         }
    theWindow.setHelpText(Translate.text("rotateMeshTool.errorText"));
    noSelection = true;
  }

  public int whichClicks()
  {
    return ALL_CLICKS;
  }

  public Image getIcon()
  {
    return icon;
  }

  public Image getSelectedIcon()
  {
    return selectedIcon;
  }

  public String getToolTipText()
  {
    return Translate.text("rotateMeshTool.tipText");
  }

  public void drawOverlay(Graphics g, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) controller.getObject().object;
    MeshVertex v[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Rectangle b;
    Vec2 p;
    int px, py;

    if (noSelection)
      return;
    g.setColor(Color.red);
    b = findScreenBounds(findSelectionBounds(v, cam), cam, (MeshViewer) view);
    p = cam.getWorldToScreen().timesXY(rotCenter);
    if (b != null)
      {
         g.fillRect(b.x, b.y, HANDLE_SIZE, HANDLE_SIZE);
         g.fillRect(b.x+b.width-HANDLE_SIZE+1, b.y, HANDLE_SIZE, HANDLE_SIZE);
         g.fillRect(b.x, b.y+b.height-HANDLE_SIZE+1, HANDLE_SIZE, HANDLE_SIZE);
         g.fillRect(b.x+b.width-HANDLE_SIZE+1, b.y+b.height-HANDLE_SIZE+1, HANDLE_SIZE, HANDLE_SIZE);
        if (!only2D)
          {
            g.fillRect(b.x+(b.width-HANDLE_SIZE)/2, b.y, HANDLE_SIZE, HANDLE_SIZE);
            g.fillRect(b.x, b.y+(b.height-HANDLE_SIZE)/2, HANDLE_SIZE, HANDLE_SIZE);
            g.fillRect(b.x+(b.width-HANDLE_SIZE)/2, b.y+b.height-HANDLE_SIZE+1, HANDLE_SIZE, HANDLE_SIZE);
            g.fillRect(b.x+b.width-HANDLE_SIZE+1, b.y+(b.height-HANDLE_SIZE)/2, HANDLE_SIZE, HANDLE_SIZE);
          }
         px = (int) p.x;
         py = (int) p.y;
         g.drawLine(px-HANDLE_SIZE, py-HANDLE_SIZE, px+HANDLE_SIZE, py+HANDLE_SIZE);
         g.drawLine(px-HANDLE_SIZE, py+HANDLE_SIZE, px+HANDLE_SIZE, py-HANDLE_SIZE);
      }
  }
  
  public void mousePressed(WidgetMouseEvent e, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) controller.getObject().object;
    MeshVertex v[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Rectangle b;
    int j, k;
    
    if (noSelection)
      return;
    clickPoint = e.getPoint();
    
    // For a control-click, just move the center of rotation.
    
    if (e.isControlDown())
      {
        double depth = cam.getWorldToView().times(rotCenter).z;
        rotCenter = cam.convertScreenToWorld(clickPoint, depth);
        view.repaint();
        notOnHandle = true;
        return;
      }
    
    // Determine which handle was clicked on.
    
    BoundingBox bounds = findSelectionBounds(v, cam);
    b = findScreenBounds(bounds, cam, (MeshViewer) view);
    notOnHandle = false;
    if (!b.contains(clickPoint))
      {
        notOnHandle = true;
        return;
      }
    if (clickPoint.x <= b.x+HANDLE_SIZE)
      j = 0;
    else if (clickPoint.x >= b.x+(b.width-HANDLE_SIZE)/2 && clickPoint.x <= b.x+(b.width-HANDLE_SIZE)/2+HANDLE_SIZE)
      j = 1;
    else if (clickPoint.x >= b.x+b.width-HANDLE_SIZE)
      j = 2;
    else j = -1;
    if (clickPoint.y <= b.y+HANDLE_SIZE)
      k = 0;
    else if (clickPoint.y >= b.y+(b.height-HANDLE_SIZE)/2 && clickPoint.y <= b.y+(b.height-HANDLE_SIZE)/2+HANDLE_SIZE)
      k = 1;
    else if (clickPoint.y >= b.y+b.height-HANDLE_SIZE)
       k = 2;
    else k = -1;
    if (j == -1 || k == -1 || (j == 1 && k == 1))
      {
         notOnHandle = true;
         return;
      }
    if (j == 1)
      {
         whichAxis = XAXIS;
         hdirection = 0;
         vdirection = -1;
      }
    else if (k == 1)
      {
         whichAxis = YAXIS;
         vdirection = 0;
         hdirection = 1;
      }
    else
      {
         whichAxis = ZAXIS;
         if (j == 0)
           vdirection = -1;
         else
           vdirection = 1;
         if (k == 0)
           hdirection = 1;
         else
           hdirection = -1;
      }
    notOnHandle = (only2D && whichAxis != ZAXIS);
    baseVertPos = mesh.getVertexPositions();
  }
  
  public void mouseDragged(WidgetMouseEvent e, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) controller.getObject().object;
    MeshVertex vert[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Point dragPoint = e.getPoint();
    Vec3 v[];
    Vec2 p;
    int i, vertSize = MeshViewer.HANDLE_SIZE;
    int selectDist[] = controller.getSelectionDistance();
    double angle;
    
    if (noSelection || notOnHandle)
      return;
    if (undo == null)
      undo = new UndoRecord(theWindow, false, UndoRecord.COPY_VERTEX_POSITIONS, new Object [] {mesh, mesh.getVertexPositions()});
    angle = DRAG_SCALE*((dragPoint.x-clickPoint.x)*hdirection + (dragPoint.y-clickPoint.y)*vdirection);
    v = findRotatedPositions(baseVertPos, angle, (MeshViewer) view);
    mesh.setVertexPositions(v);
    controller.objectChanged();
    theWindow.updateImage();
    theWindow.setHelpText(Translate.text("rotateMeshTool.dragText", Double.toString(Math.round(angle*1e5*180.0/Math.PI)/1e5)));
  }

  public void mouseReleased(WidgetMouseEvent e, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) controller.getObject().object;
    MeshVertex vert[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Point dragPoint = e.getPoint();
    int i;
    Vec3 v[];
    double angle;

    if (noSelection || notOnHandle)
      return;
    angle = DRAG_SCALE*((dragPoint.x-clickPoint.x)*hdirection + (dragPoint.y-clickPoint.y)*vdirection);
    if (undo != null)
      theWindow.setUndoRecord(undo);
    v = findRotatedPositions(baseVertPos, angle, (MeshViewer) view);
    mesh.setVertexPositions(v);
    controller.objectChanged();
    theWindow.updateImage();
    theWindow.setHelpText(Translate.text("rotateMeshTool.helpText"));
    undo = null;
    baseVertPos = null;
  }

  /* This method returns a bounding box for the selected vertices in view coordinates. */
  
  BoundingBox findSelectionBounds(MeshVertex vert[], Camera cam)
  {
    int selected[] = controller.getSelectionDistance();
    double minx, miny, minz, maxx, maxy, maxz;
    Vec3 v;
    int i;
    
    minx = miny = minz = Double.MAX_VALUE;
    maxx = maxy = maxz = -Double.MAX_VALUE;
    for (i = 0; i < vert.length; i++)
      {
         if (selected[i] == 0)
           {
             v = cam.getObjectToView().times(vert[i].r);
             if (v.x < minx) minx = v.x;
             if (v.x > maxx) maxx = v.x;
             if (v.y < miny) miny = v.y;
             if (v.y > maxy) maxy = v.y;
             if (v.z < minz) minz = v.z;
             if (v.z > maxz) maxz = v.z;
           }
      }
    return new BoundingBox(minx, maxx, miny, maxy, minz, maxz);
  }
  
  /* Given a bounding box in view coordinates, find the corresponding rectangle in
     screen coordinates. */
  
  Rectangle findScreenBounds(BoundingBox b, Camera cam, MeshViewer view)
  {
    CoordinateSystem coords = controller.getObject().coords;
    Mat4 m = cam.getObjectToWorld();
    Rectangle r;
    
    cam.setObjectTransform(cam.getViewToWorld());
    r = cam.findScreenBounds(b);
    cam.setObjectTransform(m);
    if (r != null)
      r.setBounds(r.x-10, r.y-10, r.width+20, r.height+20);
    return r;
  }

  /* Find the new positions of the vertices after scaling. */

  Vec3 [] findRotatedPositions(Vec3 vert[], double angle, MeshViewer view)
  {
    Vec3 v[] = new Vec3 [vert.length], axis;
    int selected[] = controller.getSelectionDistance();
    Camera cam = view.getCamera();
    CoordinateSystem coords = view.getDisplayCoordinates();
    Mat4 m;
    int i;
    
    // Determine whether the coordinate system is right or left handed.
    
    Vec3 xdir = cam.getWorldToView().timesDirection(Vec3.vx());
    Vec3 ydir = cam.getWorldToView().timesDirection(Vec3.vy());
    Vec3 zdir = cam.getWorldToView().timesDirection(Vec3.vz());
    if (xdir.cross(ydir).dot(zdir) < 0.0)
      angle = -angle;
    
    // Find the transformation matrix.
    
    m = coords.fromLocal();
    m = Mat4.translation(-rotCenter.x, -rotCenter.y, -rotCenter.z).times(m);
    if (whichAxis == XAXIS)
      axis = cam.getViewToWorld().timesDirection(Vec3.vx());
    else if (whichAxis == YAXIS)
      axis = cam.getViewToWorld().timesDirection(Vec3.vy());
    else
      axis = cam.getViewToWorld().timesDirection(Vec3.vz());
    m = Mat4.axisRotation(axis, angle).times(m);
    m = Mat4.translation(rotCenter.x, rotCenter.y, rotCenter.z).times(m);
    m = coords.toLocal().times(m);
    
    // Determine the deltas.
    
    for (i = 0; i < vert.length; i++)
      {
         if (selected[i] == 0)
           v[i] = m.times(vert[i]).minus(vert[i]);
         else
           v[i] = new Vec3();
      }
    if (theFrame instanceof MeshEditorWindow)
      ((MeshEditorWindow) theFrame).adjustDeltas(v);
    for (i = 0; i < vert.length; i++)
      v[i].add(vert[i]);
    return v;
  }
}